import { defineStore } from 'pinia';
import { store } from '/@/store';
import { router } from '/@/router';
import { UserInfoModel, LoginModel, UserStateModel } from '../types';
import { getUserInfoApi, loginApi, logoutApi } from '/@/api/user';
import { getTokenCache, setTokenCache, removeTokenCache } from '/@/utils/auth';

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserStateModel => ({
    // user info
    user: null,
    // token
    token: undefined,
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false,
  }),
  getters: {
    getUser(): UserInfoModel | null {
      return this.user;
    },
    getToken(): string | undefined {
      return this.token || getTokenCache();
    },
    getRoles(): string[] | undefined {
      return this.roles;
    },
    getLoadMenus(): boolean {
      return this.loadMenus;
    },
  },
  actions: {
    setToken(token: undefined | string) {
      this.token = token;
      setTokenCache(token);
    },
    setUser(info: UserInfoModel) {
      this.user = info;
    },
    setRoles(info: string[]) {
      this.roles = info;
    },
    setLoadMenus(boo: boolean) {
      this.loadMenus = boo;
    },
    resetState() {
      this.user = null;
      this.token = '';
      this.roles = [];
      this.loadMenus = false;
    },
    /**
     * @description: login
     */
    async LoginAction(params: LoginModel & { goHome?: boolean }): Promise<UserInfoModel | null> {
      try {
        const { goHome = true, ...loginParams } = params;
        // 同步登陆
        const { token, user } = await loginApi(loginParams);
        this.setToken(token);
        // 第一次加载菜单时用到
        this.setLoadMenus(true);
        await this.UserInfoAction();
        goHome && (await router.replace('/'));
        return user;
      } catch (error) {
        return null;
      }
    },
    async UserInfoAction() {
      //获取用户信息
      const res = await getUserInfoApi();
      // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
      if (res?.roles?.length === 0) {
        this.setRoles(['ROLE_SYSTEM_DEFAULT']);
      } else {
        this.setRoles(res.roles);
      }
      this.setUser(res.user);
    },
    // 登出
    async LogOutAction() {
      try {
        await logoutApi();
      } catch (error) {}
      this.resetState();
      await removeTokenCache();
      location.reload();
    },
    updateLoadMenusAction() {
      this.setLoadMenus(false);
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
